import namespace from "../namespace";
import extend from "lodash/extend";

class Rectangle extends namespace.VectorFigure {
  NAME = `${namespace.namespace}.shape.Rectangle`;

  constructor(attr, setter) {
    super();

    this.dasharray = null;

    this.setterWhitelist = extend(
      {
        dash(d) {
          return this.setDashArray(d);
        },
        dasharray(d) {
          return this.setDashArray(d);
        }
      },
      this.setterWhitelist,
      setter
    );

    super.attr(extend({}, attr));
  }

  repaint(attributes) {
    if (this.repaintBlocked === true || this.shape === null) {
      return;
    }
    attributes = extend(
      {},
      {
        width: this.getWidth(),
        height: this.getHeight(),
        r: this.getRadius()
      },
      attributes
    );

    if (this.dasharray !== null) {
      attributes["stroke-dasharray"] = this.dasharray;
    }

    super.repaint(attributes);

    return this;
  }

  applyTransformation() {
    let ts = "R" + this.rotationAngle;

    if (this.getRotationAngle() === 90 || this.getRotationAngle() === 270) {
      let ratio = this.getHeight() / this.getWidth();
      ts =
        ts +
        "S" +
        ratio +
        "," +
        1 / ratio +
        "," +
        (this.getAbsoluteX() + this.getWidth() / 2) +
        "," +
        (this.getAbsoluteY() + this.getHeight() / 2);
    }

    this.shape.transform(ts);

    return this;
  }

  createShapeElement() {
    return this.canvas.paper.rect(
      this.getAbsoluteX(),
      this.getAbsoluteY(),
      this.getWidth(),
      this.getHeight()
    );
  }

  remove() {
    this.shape.remove();
  }

  setDashArray(d) {
    this.dasharray = d;
  }

  getBoundingBox() {
    const { x, y, width: w, height: h } = this.shape.getBBox();
    return new namespace.geo.Rectangle(x, y, w, h);
  }
}

namespace.shape.Rectangle = Rectangle;
